<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="80px">
        <el-form-item label="计划年月">
          <el-date-picker
            v-model="searchParam.yearMonthPlan"
            type="month"
            placeholder="请输入年月"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="reset"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="显示行" style="margin-right: 15px">
          <el-select
            v-model="displayLines"
            placeholder="请选择显示行"
            clearable
            filterable
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            @change="changeDisplayLine"
            style="width: 270px"
            :disabled="oneDayFlag"
          >
            <el-option
              v-for="item in displayLineList"
              :key="item.num"
              :label="item.label"
              :value="item.num"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="beforeGetTableList">
            <i-ep-search />
            展示
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button type="primary" @click="validIsSearched(6)">
          新增物料
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(4)"
        >
          批量确认
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="validIsSearched(5)"
        >
          批量允许发货
        </el-button>
        <el-button type="primary" @click="validIsSearched(3)">
          导入计划</el-button
        >
        <el-button type="primary" class="ml-3" @click="downLoad">
          <template #icon><i-ep-download /></template>导出</el-button
        >-->
        <el-button
          type="success"
          :disabled="totalMultipleSelection.length === 0"
          @click="calculationPlan()"
          >智能计算</el-button
        >
        <el-button
          type="success"
          :disabled="tableData.length == 0"
          @click="stoveVerify()"
          >炉数验证</el-button
        >
        <el-button type="primary" @click="open()" v-if="!isOpen"
          >展开</el-button
        >
        <el-button type="primary" @click="close()" v-if="isOpen"
          >收起</el-button
        >
        <el-button type="primary" @click="dayPlan()">生产日计划</el-button>
        <el-button type="primary" @click="furnaceAgeConfig()"
          >炉龄配置</el-button
        >
        <el-button type="primary" @click="furnaceAgeCalculate()"
          >炉龄推算查询</el-button
        >
        <el-button type="danger" @click="dayPlanRetract()">计划撤回</el-button>
        <el-button
          type="warning"
          @click="jumpUrl()"
          :disabled="tableData.length == 0"
          >月计划统计</el-button
        >
        <el-button type="primary" plain @click="copyData()"> 计划复制 </el-button>
        <el-button type="danger" plain @click="deletedData()"> 计划删除 </el-button>
        <el-button
          class="ml-3"
          :disabled="tableData.length == 0"
          @click="
            useDownload(
              '/mes/mesplanmonth/export',
              '月度生产计划',
              selectDataStat,
              true,
              '.xls'
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <!-- 导入计划 -->
      <ImportExcel ref="weekImportRef" />

      <!-- 合计行的id定义为-999，当表格返回-999时，没有点击事件，展示合计行内容 -->

      <!-- objectSpanMethod方法，objectSpanMethod(param, 3, 7)
      参数3 代表三行合并
      参数13 代表从第13 + 1 列开始取消合并 -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        element-loading-text="数据准备中，请稍后..."
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :span-method="
          (param) => objectSpanMethod(param, displayLines.length, defaluleRow)
        "
        :header-cell-style="{ textAlign: 'center' }"
        @sort-change="onTableSortChanged"
        class="dataTable"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed
          :selectable="selectableStatus"
        />
        <el-table-column width="70" label="序号" align="center" fixed>
          <template #default="{ $index, row }">
            <span v-if="row.id !== '-999'">{{
              $index / displayLines.length + 1
            }}</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          label="产品名称"
          prop="materialName"
          width="200"
          show-overflow-tooltip
          fixed
          align="left"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="planMaterial(row)"
            >
              {{ row.materialName }}
            </span>
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="产品编码"
          prop="materialCode"
          min-width="150"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="P/M"
          prop="pm"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="M/炉"
          prop="mfurnace"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="包/炉"
          prop="bagStove"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="生产周期/天"
          prop="productionCycle"
          min-width="80"
          align="right"
          class-name="padding012"
        />
        <el-table-column
          v-if="isOpen"
          label="期初库存/件"
          prop="initialInventory"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span
              class="cursor-pointer decoration-underline p-0! can_edit_cell"
              v-if="row.id != -999"
              @click="openEditPrompt(row)"
              >{{ row.initialInventory }}</span
            >
            <span class="text-[13px]" v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="上月废品率"
          prop="lastMonthScrapRate"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.lastMonthScrapRate || 0 }}%
          </template>
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="本月订单/件"
          prop="thisMonthOrderQuantity"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <!--<template #default="{ row }">
            {{ sumThisMonthOrderQuantity(row) }}
          </template>-->
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="期末库存/件"
          prop="endStock"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <!--<template #default="{ row }">
            {{ getEndStock(row) }}
          </template>-->
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="黑件生产量/件"
          prop="blackPieceQuantity"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <!--<template #default="{ row }">
            {{ getBlackPieceQuantity(row) }}
          </template>-->
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="实时废品率"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            {{ row.dischargeHatchCode || 0 }}%
          </template>
        </el-table-column>
        <el-table-column
          v-if="isOpen"
          label="实时库存"
          prop="dischargeHatchCode"
          min-width="80"
          align="right"
          class-name="padding012"
        >
          <template #default="{ row }">
            <span class="text-[13px]" v-if="row.id != -999">{{
              row.dischargeHatchCode
            }}</span>
            <span class="text-[13px]" v-else>合计</span>
          </template>
        </el-table-column>
        <el-table-column label="大项" width="90" align="center">
          <template #default="{ $index, row }">
            <div v-for="(item, index) in displayLines" :key="index">
              <span
                class="text-[13px]"
                v-show="
                  ($index + 1) % displayLines.length ==
                    (index + 1 == displayLines.length ? 0 : index + 1) &&
                  item == 'a'
                "
                >要货数量</span
              >
              <span
                class="text-[13px]"
                v-show="
                  ($index + 1) % displayLines.length ==
                    (index + 1 == displayLines.length ? 0 : index + 1) &&
                  item == 'b'
                "
                >计划模数</span
              >
              <span
                class="text-[13px]"
                v-show="
                  ($index + 1) % displayLines.length ==
                    (index + 1 == displayLines.length ? 0 : index + 1) &&
                  item == 'c'
                "
                >完成数量</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(dayItem, dayIndex) in intervalDayList"
          :key="dayIndex"
          :label="`${dayItem.date}\n${dayItem.week}`"
          :label-class-name="
            dayItem.week == 0 || dayItem.week == 6 ? 'bg-free' : ''
          "
          min-width="65"
          align="right"
        >
          <template #header="{ column }">
            <span @click="oneDay(dayItem)" class="cursor-pointer cellNumber">{{
              column.label
            }}</span>
          </template>
          <template #default="{ row, $index }">
            <div
              :style="{
                backgroundColor:
                  inConsistentOne(
                    row,
                    $index,
                    dayItem,
                    displayLines.length,
                    one
                  ) == ''
                    ? ''
                    : inConsistentOne(
                        row,
                        $index,
                        dayItem,
                        displayLines.length,
                        one
                      ),
              }"
              v-for="(one, i) in displayLines"
              :key="i"
            >
              <!-- 要货数量 -->
              <div
                v-show="
                  ($index + 1) % displayLines.length ==
                    (i + 1 == displayLines.length ? 0 : i + 1) && one == 'a'
                "
                style="height: 25px"
              >
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                  @click="updateColour(row, intervalDayList[dayIndex])"
                >
                  <div v-for="(item, index) in row.details" :key="index">
                    <span
                      v-if="getMonthAndDay(item.requireDate) === dayItem.date"
                    >
                      {{ row.details[index]?.quantity || "" }}
                    </span>
                  </div>
                </span>
                <!--<span v-else>
                  {{ row.details[dayIndex]?.quantity }}
                </span>-->
              </div>
              <!-- 计划模数 -->
              <div
                v-show="
                  ($index + 1) % displayLines.length ==
                    (i + 1 == displayLines.length ? 0 : i + 1) && one == 'b'
                "
                @click="clickJudge(row, intervalDayList[dayIndex])"
                style="height: 25px"
              >
                <span
                  v-if="row.id !== '-999'"
                  class="cursor-pointer cellNumber"
                >
                  <div v-for="(item, index) in row.listPlanActual" :key="index">
                    <span
                      v-if="getMonthAndDay(item.requireDate) === dayItem.date"
                    >
                      {{ row.listPlanActual[index]?.planQuantity }}
                    </span>
                  </div>
                </span>
                <!--<span v-else>
                  {{ row.listPlanActual[dayIndex]?.planQuantity }}
                </span>-->
              </div>
              <!-- 完成数量 -->
              <div
                v-show="
                  ($index + 1) % displayLines.length ==
                    (i + 1 == displayLines.length ? 0 : i + 1) && one == 'c'
                "
                style="height: 25px"
              >
                <span v-if="row.id !== '-999'">
                  <!--class="cursor-pointer cellNumber"
                  @click="openFeedbackInfo(row.id,'完成信息')"-->
                  <div v-for="(item, index) in row.listPlanActual" :key="index">
                    <span
                      v-if="getMonthAndDay(item.requireDate) === dayItem.date"
                    >
                      {{ row.listPlanActual[index]?.finishQuantity || "" }}
                    </span>
                  </div>
                </span>
                <!--<span v-else>
                  {{ row.listPlanActual[dayIndex]?.finishQuantity }}
                </span>-->
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增物料弹窗 -->
    <plan-purchase-demand-add-dialog
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      @reset-table="getTableList(1)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 产品详情 -->
    <plan-material-dialog
      :visible="addNewDialog.visible"
      :title="addNewDialog.title"
      :materialId="addNewDialog.materialId"
      :data="addNewDialog.data"
      @reset-table="getTableList(1)"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 预留 -->
    <plan-require-goods-add-dialog
      :visible="addGoodsDialog.visible"
      :title="addGoodsDialog.title"
      :id="addGoodsDialog.id"
      :cellId="addGoodsDialog.cellId"
      :endDate="addGoodsDialog.endDate"
      :beginDate="addGoodsDialog.beginDate"
      :data="addGoodsDialog.data"
      @reset-table="getTableList(1)"
      :is-readonly="addGoodsDialog.readvisible"
      @change-visible="changeVisible"
    />

    <!-- 计划模数修改 -->
    <plan-feedback-info-dialog
      :visible="feedbackDialog.visible"
      :title="feedbackDialog.title"
      :cellId="feedbackDialog.cellId"
      :demandStatus="feedbackDialog.demandStatus"
      :endDate="feedbackDialog.endDate"
      :begirate="feedbackDialog.beginDate"
      :data="feedbackDialog.data"
      @reset-table="getTableList(1)"
      :is-readonly="feedbackDialog.readvisible"
      @change-visible="changeVisible"
    />
    <generation-day-plan
      :visible="dayPlanDialog.visible"
      :title="dayPlanDialog.title"
      :data="dayPlanDialog.data"
      @change-visible="changeVisible"
    />
    <plan-retract
      :visible="planRetractDialog.visible"
      :title="planRetractDialog.title"
      :data="planRetractDialog.data"
      @change-visible="changeVisible"
    />
    <!--炉龄推算-->
    <furnace-age-calculate-query
      :visible="furnaceAgeCalculateDialog.visible"
      :title="furnaceAgeCalculateDialog.title"
      :data="furnaceAgeCalculateDialog.data"
      @change-visible="changeVisible"
    />
    <stove-quantity-verify
      :visible="stoveVerifyDialog.visible"
      :title="stoveVerifyDialog.title"
      :data="stoveVerifyDialog.data"
      @change-visible="changeVisible"
    />
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table ref="uploadErrorRef" :errorDataList="errorDataList" />

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />

    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="'月度计划复制'"
      width="30%"
      top="15%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <div class="search-container">
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="复制区间"
                prop="createTimeStart"
                label-width="120px"
                style="width: 96%"
              >
                <el-date-picker
                  v-model="formData.createTimeSearch"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="handleDateChange"
                  :disabled-date="disabledDate"
                  @calendar-change="handleCalendarChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="数据来源日期"
                prop="createTime"
                label-width="120px"
                style="width: 96%"
              >
                <el-date-picker
                  v-model="formData.createTime"
                  type="date"
                  placeholder="请选择数据来源日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :loading="loadingDialog"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialogDeleted"
      :title="'月度计划删除'"
      width="30%"
      top="15%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <div class="search-container">
          <el-row>
            <!--<el-col :span="24">
              <el-form-item
                label="删除日期"
                prop="deletedTime"
                label-width="120px"
                style="width: 96%"
              >
                <el-date-picker
                  v-model="formData.deletedTime"
                  type="date"
                  placeholder="请选择删除日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>-->
            <el-col :span="24">
              <el-form-item
                label="删除区间"
                prop="createTimeStart"
                label-width="120px"
                style="width: 96%"
              >
                <el-date-picker
                  v-model="formData.createTimeSearch"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="handleDateChange"
                  :disabled-date="disabledDate"
                  @calendar-change="handleCalendarChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :loading="loadingDialog"
            @click="handleSubmitDeleted"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  SearchInterface,
  TableResultObject,
  ScheduleList,
} from "./utilejs/interface";
import {
  resolveSearchData,
  objectSpanMethod,
  getDaysByMonth,
  selectableStatus,
  inConsistent,
  inConsistentOne,
} from "./utilejs/index";
import { filterOrder, promptValidateNumber } from "@/utils/commonHooks";
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDownload, useDictionary } from "@/utils/useTable";
import { getNextMonth } from "@/views/mes/rawmaterialneedplan/planmonthrawmaterial/utilejs";
import router from "@/router";

defineOptions({
  name: "MESMESPLANMONTH",
  inheritAttrs: false,
});

// 初始化搜索参数数据
const searchParam = reactive<SearchInterface>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: getCurrentMonth(),
});

// 点击搜索按钮后被保存的搜索数据
const searchedParam = reactive<SearchInterface>({
  materialId: "",
  materialCode: "",
  yearMonthPlan: "",
});

// 搜索时间变化后处理函数
const intervalDayList = ref<any[]>([]);

// 行复选框选中后处理
const ids = ref<string[]>([]);
const dataTableRef = ref();
// 表格选择
const totalMultipleSelection: any = ref([]);
function handleSelectionChange(selection: TableResultObject[]) {
  // ids.value = selection.map((item: TableResultObject) => item.id);
  totalMultipleSelection.value = selection;
}

// 开始展示逻辑处理
const loading = ref(false);
const isOpen = ref(true);
const defaluleRow = ref(15);
const tableData = ref([]);
const selectDataStat = ref([]);
// 点击展示之前
function beforeGetTableList() {
  if (!searchParam.yearMonthPlan) {
    ElMessage.error("请选择计划月");
    return;
  }
  getTableList(1);
}

// 点击展示之后
async function getTableList(isReset = 0) {
  // isReset为 1 加载刷新、0 无感知刷新
  if (isReset === 1) {
    dataTableRef.value.setScrollTop(0);
    loading.value = true;
  }
  const { data }: any = await request({
    url: "/mes/mesplanmonth/queryByList",
    method: "post",
    data: isReset === 0 ? toRaw(searchedParam) : toRaw(searchParam),
  }).catch(() => {});

  selectDataStat.value = data;

  // 储存被搜索条件
  Object.assign(searchedParam, {
    ...toRaw(searchParam),
  });
  if (!oneDayFlag.value) {
    // 时间处理
    intervalDayList.value = getDaysByMonth(searchParam.yearMonthPlan);
  }
  // 数据处理
  let line = displayLineList.value.length;
  if (displayLines.value.length != 0) {
    line = displayLines.value.length;
  }
  //是否筛选
  if (oneDayFlag.value) {
    oneDayFlag.value = false;
  }
  startData.value = data;
  tableData.value = resolveSearchData(data, line);
  loading.value = false;
}
function open() {
  isOpen.value = true;
  defaluleRow.value = 14;
}
function close() {
  isOpen.value = false;
  defaluleRow.value = 3;
}
// 监听表格后台排序方法
const initParam = reactive({ sort: {} });
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };

  getTableList(1);
}

// 新增物料弹窗及操作逻辑
const addDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  addGoodsDialog.visible = value;
  feedbackDialog.visible = value;
  addNewDialog.visible = value;
  dayPlanDialog.visible = value;
  stoveVerifyDialog.visible = value;
  planRetractDialog.visible = value;
  furnaceAgeCalculateDialog.visible = value;
  if (!value) {
    addDialog.data = {};
    addGoodsDialog.data = {};
    addGoodsDialog.cellId = "";
    addGoodsDialog.id = "";
    feedbackDialog.data = {};
    feedbackDialog.cellId = "";
    addNewDialog.data = {};
    detailData = {};
    stoveVerifyDialog.data = {};
    planRetractDialog.data = {};
    furnaceAgeCalculateDialog.data = {};
  }
}

// 新增要货弹窗及操作逻辑
const addGoodsDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  id: "",
});
let detailData = reactive({
  id: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  planId: "",
  planQuantity: "",
  planQuantitySum: 0,
  thisMonthOrderQuantity: 0,
});
const updateColour = (row?: any, day) => {
  let one = null;
  row.details.forEach((item) => {
    if (getMonthAndDay(item.requireDate) === day.date) {
      one = item;
    }
  });
  if (one?.status === 1) {
    ElMessageBox.confirm("是否确认?", "警告", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        one.status = 2;
        const res: any = await request({
          url: `/mes/mesplanmonthrequire/save`,
          method: "post",
          data: one,
        });
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "确认成功",
          });
          getTableList(1);
        }
      })
      .catch(() => {});
  }
};

// 反馈信息确认弹窗及操作逻辑
const feedbackDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  endDate: "",
  beginDate: "",
  cellId: "",
  demandStatus: null,
});
// 生成日计划
const dayPlanDialog = reactive<any>({
  visible: false,
  title: "",
  data: {},
});
const stoveVerifyDialog = reactive<any>({
  visible: false,
  title: "",
  data: {},
});
const openFeedbackInfo = (
  cellId = "",
  title = "",
  demandStatus = null,
  contentNumber = null,
  row: any,
  day
) => {
  console.log("day", day.date);
  detailData.planId = row.id;
  detailData.materialId = row.materialId;
  detailData.materialCode = row.materialCode;
  detailData.materialName = row.materialName;
  detailData.requireDate = row.yearMonthPlan + "-" + day.date.slice(3, 5);
  detailData.thisMonthOrderQuantity = row.thisMonthOrderQuantity;
  detailData.pm = row.pm;
  detailData.mfurnace = row.mfurnace;
  if (!row.lastMonthScrapRate) {
    row.lastMonthScrapRate = 0;
  }
  detailData.lastMonthScrapRate = row.lastMonthScrapRate;
  detailData.planQuantitySum = 0;
  let flag = true;
  let one = null;
  row.listPlanActual.forEach((item) => {
    detailData.planQuantitySum +=
      item?.planQuantity * (1 - row.lastMonthScrapRate * 0.01) * row.pm;
    if (getMonthAndDay(item.requireDate) === day.date) {
      detailData.id = item.id;
      detailData.planQuantity = item.planQuantity;
      detailData.planQuantitySum -=
        item.planQuantity * (1 - row.lastMonthScrapRate * 0.01) * row.pm;
      one = item;
      flag = false;
    }
  });
  //去除数据处理后id相同的数据
  let arr = tableData.value.filter(
    (item, index, self) => self.findIndex((i) => i.id === item.id) === index
  );
  arr
    .map((item) => item.listPlanActual)
    .flat()
    .filter((item) => getMonthAndDay(item.requireDate) === day.date)
    .forEach((item) => {
      if (item.status === 1) {
        one = item;
      }
    });
  if (
    new Date(getCurrentDate()) >
    new Date(row.yearMonthPlan + "-" + day.date.slice(3, 5))
  ) {
    ElMessage.error("只能修改当天和当天以后数据！");
    return;
  }
  if (one?.status === 1) {
    ElMessage.error("日计划已生成或当天存在已生成日计划，不可编辑！");
    return;
  }
  if (flag) {
    detailData.id = "";
    detailData.planQuantity = 0;
  }
  const object = {
    visible: true,
    title: title,
    beginDate: dayjs(searchedParam.yearMonthPlan)
      .startOf("month")
      .format("YYYY-MM-DD"),
    endDate: dayjs(searchedParam.yearMonthPlan)
      .endOf("month")
      .format("YYYY-MM-DD"),
    cellId: cellId,
    demandStatus: demandStatus,
    contentNumber: contentNumber == null ? "" : contentNumber,
    data: detailData,
  };
  Object.assign(feedbackDialog, { ...object });
};
async function openFeedbackInfoTwo(row: any, day) {
  loading.value = true;
  detailData.planId = row.id;
  detailData.materialId = row.materialId;
  detailData.materialCode = row.materialCode;
  detailData.materialName = row.materialName;
  detailData.requireDate = row.yearMonthPlan + "-" + day.date.slice(3, 5);
  detailData.thisMonthOrderQuantity = row.thisMonthOrderQuantity;
  detailData.pm = row.pm;
  detailData.mfurnace = row.mfurnace;
  if (!row.lastMonthScrapRate) {
    row.lastMonthScrapRate = 0;
  }
  detailData.lastMonthScrapRate = row.lastMonthScrapRate;
  detailData.planQuantitySum = 0;
  let flag = true;
  let one = null;
  row.listPlanActual.forEach((item) => {
    detailData.planQuantitySum +=
      item?.planQuantity * (1 - row.lastMonthScrapRate * 0.01) * row.pm;
    if (getMonthAndDay(item.requireDate) === day.date) {
      console.log("day.date", day.date, item);
      detailData.id = item.id;
      detailData.planQuantity = item.planQuantity;
      detailData.planQuantitySum -=
        item.planQuantity * (1 - row.lastMonthScrapRate * 0.01) * row.pm;
      one = item;
      flag = false;
    }
  });
  if (detailData.planQuantity > 0) {
    loading.value = false;
    console.log("数量大于0不触发双击赋值");
    return;
  }
  //去除数据处理后id相同的数据
  let arr = tableData.value.filter(
    (item, index, self) => self.findIndex((i) => i.id === item.id) === index
  );
  arr
    .map((item) => item.listPlanActual)
    .flat()
    .filter((item) => getMonthAndDay(item.requireDate) === day.date)
    .forEach((item) => {
      if (item.status === 1) {
        one = item;
      }
    });
  if (
    new Date(getCurrentDate()) >
    new Date(row.yearMonthPlan + "-" + day.date.slice(3, 5))
  ) {
    ElMessage.error("只能修改当天和当天以后数据！");
    loading.value = false;
    return;
  }
  if (one?.status == 1) {
    ElMessage.error("日计划已生成或当天存在已生成日计划，不可编辑！");
    loading.value = false;
    return;
  }
  if (flag) {
    detailData.id = "";
    detailData.planQuantity = 0;
  }
  detailData.planQuantity = row.mfurnace;
  await request({
    url: "/mes/mesplanmonthplanactual/save",
    method: "post",
    data: detailData,
  }).finally(() => {});
  ElMessage.success(`成功`);
  await getTableList(1);
  detailData = {};
}
// 获取当前日期yyyy - mm
function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  return year + "-" + month;
}
// 获取当前日期yyyymmdd
function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  return year + "-" + month + "-" + day;
}
// 操作前校验是否搜索过
function validIsSearched(type: number) {
  if (!searchedParam.yearMonthPlan) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    // 导入计划
    if (type === 3) {
      weekBatchImport();
    }

    // 批量确认
    if (type === 4) {
      confirmBatch();
    }

    // 批量允许发货
    if (type === 5) {
      sendAbleBatch();
    }

    // 新增物料(新版)
    if (type === 6) {
      openAddMaterialNew();
    }
  }
}

// 导入计划
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/srm/srmmaterialdemand/upload", formdata, config)
    .then((res: any) => {
      weekImportRef.value.resCode = res.code;
      if (res.code === 300) {
        errorDataList.value = res.data;
        uploadErrorRef.value.errorBox = true;
      }
    })
    .catch((e) => {
      weekImportRef.value.resCode = 500;
    });
}
const weekBatchImport = () => {
  let params = {
    title: "导入计划",
    tempApi: "", //模板下载
    importApi: weekImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {
      yearMonthPlan: searchedParam.yearMonthPlan,
    },
  };
  weekImportRef.value.acceptParams(params);
};

// 导出
const downLoad = () => {
  if (!searchedParam.yearMonthPlan) {
    ElMessage.error("请先选择计划月后，再进行操作");
    return;
  } else {
    useDownload(
      "/srm/srmmaterialdemand/export",
      "采购需求",
      searchParam,
      true,
      ".xls"
    );
  }
};

function confirmBatch() {
  ElMessageBox.confirm("请确认，是否继续批量确认操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/confirmBatch",
          method: "post",
          data: {
            yearMonthPlan: searchedParam.yearMonthPlan,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量确认成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}

function sendAbleBatch() {
  ElMessageBox.confirm("请确认，是否继续批量允许发货操作?", "提示", {
    confirmButtonText: "确 认",
    cancelButtonText: "取 消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        // 全部反馈接口加载成功
        instance.confirmButtonLoading = true;
        const res: any = await request({
          url: "/srm/srmdemandschedule/sendAbleBatch",
          method: "post",
          data: {
            yearMonthPlan: searchedParam.yearMonthPlan,
            ids: ids.value,
          },
        }).catch(() => {
          instance.confirmButtonLoading = false;
          done();
        });
        if (res?.code === 200) {
          ElMessage.success("批量允许发货成功");
          getTableList(1);
        }
        instance.confirmButtonLoading = false;
        done();
      } else {
        done();
      }
    },
  })
    .then(() => {})
    .catch(() => {});
}
// 新增物料（新版）弹窗及操作逻辑
const addNewDialog = reactive<any>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  materialId: "",
});
const planMaterial = (row) => {
  const object = {
    visible: true,
    title: "产品详情",
    materialId: row.materialId,
  };
  Object.assign(addNewDialog, { ...object });
};

const openEditPrompt = (row: any) => {
  ElMessageBox.prompt("期初库存（件）", row.materialName, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "prompt_custom",
    closeOnClickModal: false,
    inputValue: String(row.initialInventory),
    inputValidator: (value: string) =>
      initialInventoryPromptValidateNumber(value),
  })
    .then(async ({ value }) => {
      row.initialInventory = value;
      const res = await request({
        url: "/mes/mesplanmonth/save",
        method: "post",
        data: row,
      });
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: `修改成功`,
        });
        getTableList(1);
      }
    })
    .catch(() => {});
};
const getyearMonthPlan = async () => {
  const { data }: any = await request({
    url: "/mes/mesyearMonthPlan/queryByList",
    method: "post",
    data: data,
  });
  return data;
};
function getMonthAndDay(date: any) {
  let month = date.slice(5, 7);
  let day = date.slice(8, 10);
  return month + "/" + day;
}
//计算本月订单数量 = 要货数量合计
function sumThisMonthOrderQuantity(row: any) {
  var sum = 0;
  if (row.details.length > 0) {
    row.details.forEach((item: any) => {
      sum += item.quantity;
    });
  } else {
    sum = 0;
  }
  return sum;
}
//期末库存 = 总模数*每模多少个*（1-废品率）+期初库存-本月订单量
function getEndStock(row: any) {
  return (
    row.mfurnace * row.pm * ((100 - row.lastMonthScrapRate) * 0.01) +
    row.initialInventory -
    sumThisMonthOrderQuantity(row)
  );
}
//黑件生产量 = 计划总模数*每模多少个
function getBlackPieceQuantity(row: any) {
  var sum = 0;
  if (row.details.length > 0) {
    row.listPlanActual.forEach((item: any) => {
      sum += item.planQuantity;
    });
    sum = sum * row.pm;
  } else {
    sum = 0;
  }
  return row.mfurnace * row.pm;
}
const calculationPlan = async () => {
  ElMessageBox.confirm("确定对已选择数据进行智能计算吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesplanmonth/calculationPlan",
        method: "post",
        data: totalMultipleSelection.value,
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "计算完成",
        });
      }
      await getTableList(1);
    })
    .catch(() => {});
};
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.materialId = data.id;
    searchParam.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);

// 重置搜索条件
const reset = () => {
  searchParam.materialId = "";
  searchParam.materialCode = "";
};
function dayPlan() {
  dayPlanDialog.title = "生成日计划";
  dayPlanDialog.visible = true;
}
function stoveVerify() {
  stoveVerifyDialog.title = "炉数验证";
  stoveVerifyDialog.visible = true;
  stoveVerifyDialog.data.intervalDayList = intervalDayList.value;
  stoveVerifyData();
}
function stoveVerifyData() {
  let arr = [];
  //去除数据处理后id相同的数据
  arr = tableData.value.filter(
    (item, index, self) => self.findIndex((i) => i.id === item.id) === index
  );
  let stoveData = [];
  intervalDayList.value.forEach((item) => {
    let rowSum = 0;
    arr.forEach((row) => {
      row.listPlanActual.forEach((one: any) => {
        if (item.date == getMonthAndDay(one.requireDate)) {
          rowSum += one.planQuantity / row.mfurnace;
        }
      });
    });
    let s = rowSum.toFixed(1);
    if (s.toString().endsWith(".0")) {
      stoveData.push(s.split(".")[0]); // 去掉 ".0"
    } else {
      stoveData.push(s); // 保留小数部分
    }
  });
  stoveVerifyDialog.data.stoveData = stoveData;
  console.log("stoveData", stoveData);
}
// 生成日计划
const planRetractDialog = reactive<any>({
  visible: false,
  title: "",
  data: {},
});
function dayPlanRetract() {
  planRetractDialog.title = "计划撤回";
  planRetractDialog.visible = true;
}
const furnaceAge = ref();
const furnaceAgeConfig = () => {
  ElMessageBox.prompt("炉龄配置", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    customClass: "prompt_custom",
    closeOnClickModal: false,
    inputValue: furnaceAge.value,
    inputValidator: (value: string) => promptValidateNumber(value),
  })
    .then(async ({ value }) => {
      furnaceAge.value = value;
      ElMessage({
        type: "success",
        message: `配置成功`,
      });
    })
    .catch(() => {});
};
// 炉龄推算
const furnaceAgeCalculateDialog = reactive<any>({
  visible: false,
  title: "",
  data: {},
});
async function furnaceAgeCalculate() {
  furnaceAgeCalculateDialog.title = "炉龄推算";
  furnaceAgeCalculateDialog.data.furnaceAge = furnaceAge.value;
  let stoveDataAll = await getStoveDataAll();
  await getFurnaceAgeData(stoveDataAll);
}
// 获取当月炉数与下月炉数
async function getStoveDataAll() {
  let arr = [];
  // 获取当前年月
  let yearMonthPlan = getCurrentDate().substring(0, 7);
  //当月日期与数据
  let intervalDayList = getDaysByMonth(yearMonthPlan);
  arr = await queryByList(yearMonthPlan);
  let stoveDataAll = [];
  for (let i = 0; i < 2; i++) {
    let stoveData = [];
    // 下月日期与数据
    if (i == 1) {
      yearMonthPlan = getNextMonth(yearMonthPlan);
      intervalDayList = getDaysByMonth(yearMonthPlan);
      // X轴日期
      let arrXdata = [];
      intervalDayList.forEach((item) => {
        arrXdata.push(item.date);
      });
      furnaceAgeCalculateDialog.data.xdata = arrXdata;
      // 控制线
      if (furnaceAge.value || furnaceAge.value > 0) {
        let arry = [];
        for (let i = 0; i < arrXdata.length; i++) {
          arry.push(furnaceAge.value);
        }
        furnaceAgeCalculateDialog.data.ydata3 = arry;
      }
      arr = await queryByList(yearMonthPlan);
    }
    intervalDayList.forEach((item) => {
      let rowSum = 0;
      arr.forEach((row) => {
        row.listPlanActual.forEach((one: any) => {
          if (item.date == getMonthAndDay(one.requireDate)) {
            rowSum += one.planQuantity / row.mfurnace;
          }
        });
      });
      let s = rowSum.toFixed(1);
      if (s.toString().endsWith(".0")) {
        stoveData.push(s.split(".")[0]); // 去掉 ".0"
      } else {
        stoveData.push(s); // 保留小数部分
      }
    });
    stoveDataAll.push(stoveData);
  }
  console.log("stoveDataAll", stoveDataAll);
  return stoveDataAll;
}
async function queryByList(yearMonthPlan) {
  const { data }: any = await request({
    url: "/mes/mesplanmonth/queryByList",
    method: "post",
    data: { yearMonthPlan: yearMonthPlan },
  });
  return data;
}
// const xData = ref([]);
async function getFurnaceAgeData(stoveDataAll) {
  await request({
    url: "/mes/mesplanmonth/getFurnaceAgeData",
    method: "post",
    data: stoveDataAll,
  }).then((res) => {
    if (res.data.length > 0) {
      furnaceAgeCalculateDialog.data.yDatas = res.data;
      furnaceAgeCalculateDialog.visible = true;
    } else {
      ElMessage({
        type: "warning",
        message: "无数据",
      });
    }
  });
}
function initialInventoryPromptValidateNumber(value: any) {
  if (!value) {
    return "请输入数字";
  } else if (isNaN(parseFloat(value)) && isFinite(value)) {
    return "请输入数字";
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    return "请输入数字";
  } else if (Number(value) < 0) {
    return "请输入大于等于0的值";
  } else {
    return true;
  }
}
const displayLines = ref(["a", "b", "c"]);
const displayLineList = ref([
  {
    num: "a",
    label: "要货数量",
  },
  {
    num: "b",
    label: "计划模数",
  },
  {
    num: "c",
    label: "完成数量",
  },
]);
const startData = ref([]);
function changeDisplayLine() {
  loading.value = true;
  if (displayLines.value.length == 0) {
    displayLines.value = ["a", "b", "c"];
  }
  displayLines.value.sort();
  tableData.value = [];
  let arr = resolveSearchData(startData.value, displayLines.value.length);
  let intervalId = setInterval(() => {
    if (arr.length > 0) {
      tableData.value = arr;
      loading.value = false;
      clearInterval(intervalId);
    }
  }, 200);
}
const oneDayFlag = ref(false);
//筛选
async function oneDay(dayDate) {
  loading.value = true;
  if (oneDayFlag.value) {
    dataTableRef.value.setScrollTop(0);
    displayLines.value = ["a", "b", "c"];
    // beforeGetTableList();
    let arr = resolveSearchData(startData.value, displayLines.value.length);
    let intervalId = setInterval(() => {
      if (arr.length > 0) {
        tableData.value = arr;
        loading.value = false;
        clearInterval(intervalId);
      }
    }, 200);
    oneDayFlag.value = false;
  } else {
    oneDayFlag.value = true;
    const targetDateStr = dayDate.date; // 提前计算
    const arr = [];
    startData.value.forEach((item) => {
      item.listPlanActual?.forEach((plan) => {
        if (
          getMonthAndDay(plan.requireDate) === targetDateStr &&
          (plan.planQuantity ?? 0) !== 0
        ) {
          arr.push(item);
        }
      });
    });
    displayLines.value = ["b"];
    // tableData.value = resolveSearchData(arr, displayLines.value.length);
    let arrNew = resolveSearchData(arr, displayLines.value.length);
    let time = 0;
    let intervalId = setInterval(() => {
      time += 200;
      if (arrNew.length > 0) {
        tableData.value = arrNew;
        loading.value = false;
        clearInterval(intervalId);
      }
      if (arrNew.length == 0 && time > 10000) {
        tableData.value = arrNew;
        loading.value = false;
        clearInterval(intervalId);
      }
    }, 200);
    // loading.value = false;
  }
}
//单击双击事件
const isOne = ref(false); // 判断是否有第一次点击
const isTwo = ref(false); // 判断是否有第二次点击
const delayTime = ref(300); // 单击事件的延迟时间，同时是双击的判断阈值
const clickJudge = (row, day) => {
  console.log("isOne.value", isOne.value);
  console.log("isTwo.value", isTwo.value);
  if (!isOne.value) {
    // 如果是第一次点击
    isTwo.value = false; // 重置双击判断函数
    isOne.value = true;
    setTimeout(() => {
      // 如果延迟函数期间执行了第二次点击 则不执行单击事件
      if (!isTwo.value) {
        OneClick(row, day);
        isOne.value = false;
      }
    }, delayTime.value);
  } else {
    //  如果已经有第一次点击了 接下来便是第二次点击
    isTwo.value = true;
    TwoClick(row, day);
    // 双击执行完之后 需要重置判断属性
    isOne.value = false; // 重置单击判断函数
  }
};
const OneClick = (row, day) => {
  openFeedbackInfo(row.id, "计划信息", null, null, row, day);
  // 单击事件代码
  console.log("我被单击了");
};
const TwoClick = (row, day) => {
  openFeedbackInfoTwo(row, day);
  // 双击事件代码
  console.log("我被双击了");
};

function jumpUrl() {
  if (searchParam.yearMonthPlan) {
    router.push({
      path: "/mes/mesplanmonthstatistics",
      query: { yearMonthPlan: searchParam.yearMonthPlan },
    });
  }
}
//复制 删除
const loadingDialog = ref(false);
const formRef = ref(ElForm);
function copyData() {
  visibleDialog.value = true;
}
function deletedData() {
  visibleDialogDeleted.value = true;
}
let formData = reactive({
  createTime: "",
  createTimeStart: "",
  createTimeEnd: "",
  createTimeSearch: [],
  deletedTime: "",
});
/** 弹窗显示 **/
const visibleDialog = ref(false);
const visibleDialogDeleted = ref(false);
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      //判断开始时间是否在开始与结束时间之内
      let startTime = new Date(formData.createTimeStart);
      let time = new Date(formData.createTime);
      if (startTime.getFullYear() != time.getFullYear() || startTime.getMonth() != time.getMonth()) {
        ElMessage.error("复制区间与数据来源日期不在同一月内！");
        return;
      }
      loadingDialog.value = true;
      await ElMessageBox.confirm("原有已存在数据可能会被覆盖！", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            // 开启按钮加载
            instance.confirmButtonLoading = true;
            await request({
              url: `/mes/mesplanmonth/saveCopy`,
              method: "post",
              data: formData,
            })
              .then((res) => {
                ElMessage({
                  type: res.code == 200 ? "success" : "error",
                  message: res.code == 200 ? "复制成功！" : res.message,
                });
                loadingDialog.value = false;
                closeDialog();
              })
              .catch((res) => {
                done();
                loadingDialog.value = false;
              });
            getTableList(1);
          }
          done();
          loadingDialog.value = false;
        },
      });
    }
  });
}
function handleSubmitDeleted() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loadingDialog.value = true;
      await ElMessageBox.confirm("请确认是否删除该日期数据！", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            // 开启按钮加载
            instance.confirmButtonLoading = true;
            await request({
              url: `/mes/mesplanmonth/saveDelete`,
              method: "post",
              data: formData,
            })
              .then((res) => {
                ElMessage({
                  type: res.code == 200 ? "success" : "error",
                  message: res.code == 200 ? "删除成功！" : res.message,
                });
                loadingDialog.value = false;
                closeDialog();
              })
              .catch((res) => {
                done();
                loadingDialog.value = false;
              });
            getTableList(1);
          }
          done();
          loadingDialog.value = false;
          closeDialog();
        },
      });
    }
  });
}
function closeDialog() {
  visibleDialog.value = false;
  visibleDialogDeleted.value = false;
  formData.createTimeSearch = "";
  formData.createTime = "";
  formData.createTimeStart = "";
  formData.createTimeEnd = "";
  formData.deletedTime = "";
  formRef.value.resetFields();
  formRef.value.clearValidate();
  currentStartDate.value = null;
}
const rules = reactive({
  createTime: [
    { required: true, message: "请选择物料来源数据", trigger: "change" },
  ],
  createTimeStart: [
    { required: true, message: "请选择开始日期与结束日期", trigger: "change" },
  ],
  createTimeEnd: [],
  deletedTime: [
    { required: true, message: "请选择删除时间", trigger: "change" },
  ],
});
function getBeginTimeLocal(data: any) {
  if (data) {
    formData.createTimeStart = data[0];
    formData.createTimeEnd = data[1];
  } else {
    formData.createTimeStart = "";
    formData.createTimeEnd = "";
  }
}

// 存储当前选中的开始日期（用于动态限制结束日期）
const currentStartDate = ref(null);

// 处理日期范围变化
const handleDateChange = (dates) => {
  currentStartDate.value = null;
  disabledDate();
  if (dates && dates.length === 2) {
    const [start, end] = dates;
    const startDate = new Date(start);
    const endDate = new Date(end);
    const diffTime = Math.abs(endDate - startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // 包含起始日
    formData.createTimeStart = start;
    formData.createTimeEnd = end;
    if (diffDays > 31) {
      // 如果超过31天，自动重置为合法范围
      const newEndDate = new Date(startDate);
      newEndDate.setDate(startDate.getDate() + 30);
      formData.value.createTimeSearch = [
        start,
        newEndDate.toISOString().split("T")[0],
      ];
      ElMessage.warning("日期范围不能超过31天");
    }
  }
};

// 处理日历选择变化（用户点击选择开始日期时）
const handleCalendarChange = (dates) => {
  if (dates && dates[0]) {
    currentStartDate.value = new Date(dates[0]);
  }
};

const disabledDate = (time) => {
  if (!currentStartDate.value) return false;

  const startDate = new Date(currentStartDate.value);
  const minEndDate = new Date(startDate); // 最小结束日期=开始日期
  const maxEndDate = new Date(startDate);
  // maxEndDate.setDate(startDate.getDate() + 30); // 最大结束日期=开始日期+30天
  maxEndDate.setMonth(startDate.getMonth() + 1, 0); //获取开始时间所在月的最后一天
  // 禁用逻辑：
  // 1. 对于结束日期选择器：只能选择 >= 开始日期 且 <= 开始日期+30天/当月最后一天
  return time < minEndDate || time > maxEndDate;
};
</script>

<style lang="scss" scoped>
// 所有表格样式
:deep(.dataTable) {
  .el-scrollbar__bar.is-horizontal {
    height: 12px;
    left: 2px;
  }
  .el-table__body td.el-table__cell {
    padding: 0;
    .can_edit_cell:hover {
      color: #409eff !important;
    }
  }
  .cell {
    padding: 0;
    white-space: pre-wrap;
  }
  .padding012 .cell {
    padding: 0 12px !important;
  }
  td.el-table__cell .cell {
    padding: 3px 12px;
  }

  .el-scrollbar__wrap {
    max-height: calc(100vh - 342px);
    overflow-y: scroll;
  }

  .seltAllbtnDis .cell {
    visibility: hidden;
  }
  .el-table__empty-block {
    height: 120px !important;
  }
}

:deep(.el-table--border th.bg-free) {
  background-color: rgb(239.8, 248.9, 235.3) !important;
}

// 红色标识
.c-red-font {
  background-color: #fef1f1 !important;
  span {
    // color: lightcoral;
    color: brown !important;
  }
}

// 绿色标识
.c-green {
  background: #55efc4 !important;
  span {
    color: #2f4f4f !important;
  }
}

.cellNumber:hover {
  text-decoration: underline;
}
</style>
